﻿using CommunityToolkit.Mvvm.Input;
using Newtonsoft.Json;
using Prism.Commands;
using Prism.Events;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ZoneLineNew.Controls;
using ZoneLineNew.Core.EventArgs;
using ZoneLineNew.Core.Utils;
using ZoneLineNew.Models.Entity.Template;
using ZoneLineNew.Models.PrintResult;
using ZoneLineNew.Models.StationConfig;
using ZoneLineNew.Services.DB;
using ZoneLineNew.Services.Message;
using ZoneLineNew.Services.Print;
using ZoneLineNew.ViewModelBase;

namespace ZoneLineNew.ViewModels {
    internal class LabelPrintViewModel : NavigationViewModel {

        private readonly PrinterLabelService _printerService;

        public LabelPrintViewModel(
            IRegionManager regionManager,
            IDialogService dialog,
            IMessageService messageBox,
            IEventAggregator eventAggregator,
            IDbOperate<IFreeSqlMainContext> mainDbOperate,
            PrinterLabelService printerService
            ) : base(regionManager, dialog, messageBox, eventAggregator, mainDbOperate) {
            _printerService = printerService;
           
        }

        #region Props
        private string _searchText = "";

        public string SearchText {
            get { return _searchText; }
            set { _searchText = value; base.RaisePropertyChanged(); }
        }

        private ObservableCollection<AbsPrintResult> _absPrintResults = new ObservableCollection<AbsPrintResult>();

        public ObservableCollection<AbsPrintResult> AbsPrintResults {
            get { return _absPrintResults; }
            set { _absPrintResults = value; base.RaisePropertyChanged(); }
        }


        private ObservableCollection<LableCompenState> _reAbsPrintResults = new ObservableCollection<LableCompenState>();

        public ObservableCollection<LableCompenState> ReAbsPrintResults {
            get { return _reAbsPrintResults; }
            set { _reAbsPrintResults = value; base.RaisePropertyChanged(); }
        }

        private AbsPrintResult _selectPrintResult;

        public AbsPrintResult SelectPrintResult {
            get { return _selectPrintResult; }
            set { _selectPrintResult = value; base.RaisePropertyChanged(); }
        }

        private ObservableCollection<string> _printNames = new ObservableCollection<string>();

        public ObservableCollection<string> PrintNames {
            get { return _printNames; }
            set { _printNames = value; base.RaisePropertyChanged(); }
        }

        private string _selectPrinterName;

        public string SelectPrinterName {
            get { return _selectPrinterName; }
            set { _selectPrinterName = value; base.RaisePropertyChanged(); }
        }
        #endregion

        public DelegateCommand SearchCommand => new DelegateCommand(() => {
            AbsPrintResults.Clear();
            ReAbsPrintResults.Clear();
            if (string.IsNullOrWhiteSpace(SearchText)) {
                _message.Warning("请输入查询码！");
                return;
            }

            var list = _mainDbOperate.GetModelList<AbsPrintResult>(a => a.AbsCode.Contains(SearchText) || a.Code.Contains(SearchText));
            if (!list.Any()) {
                _message.Info("未查询到当前产品的标签信息！");
                return;
            }

            AbsPrintResults.Clear();
            AbsPrintResults.AddRange(list);

            var list2 = _mainDbOperate.GetModelList<LableCompenState>(a => a.AbsCode.Contains(SearchText) || a.Code.Contains(SearchText));
            ReAbsPrintResults.Clear();
            ReAbsPrintResults.AddRange(list2);
        });

       

        public DelegateCommand<AbsPrintResult> RePrintCommand => new DelegateCommand<AbsPrintResult>((rhs) => {
            if (string.IsNullOrEmpty(SelectPrinterName)) {
                _message.Error("请选择打印机！");
                return;
            }

            var temp = _mainDbOperate.GetModel<TemplateEntity>(o => o.ProductID == rhs.ProductID && o.TemplateType == Enums.eTemplateType.LabelCode);
            if (rhs != null && temp != null) {
                var dialogAsk = _message.Ask($"确定是否重新打印记录为【{rhs.Id}】的二维码标签？");
                if (dialogAsk == System.Windows.MessageBoxResult.OK) {
                    var dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(rhs.PrintParams);
                    var res = _printerService.RePrintLabel(temp, SelectPrinterName, rhs.Code, dic, absScanCode: rhs.AbsCode);
                    if (res) {
                        _message.GrowSuccess("标签重打成功！");
                        //打印成功，将数据打印的数据记录到关联表中
                        LableCompenState lableCompenState = JsonConvert.DeserializeObject<LableCompenState>(JsonConvert.SerializeObject(rhs));
                        lableCompenState.PrintTime = DateTime.Now;
                        _mainDbOperate.AddModel<LableCompenState>(lableCompenState);
                    }
                }
            } else {
                _message.Error("重打失败，未找到此记录关联的产品！");
            }
        });



        protected override void OnViewLoaded() {
            var plist = PrinterUtil.GetAllPrinterNames();
            PrintNames.Clear();
            PrintNames.AddRange(plist);

            _eventAggregator.GetEvent<PubSubEventArgs>().Unsubscribe(GetScanBarCode);
            _eventAggregator.GetEvent<PubSubEventArgs>().Subscribe(GetScanBarCode);
            //base.OnViewLoaded();
        }

        public override void OnNavigatedFrom(NavigationContext navigationContext) {
            _eventAggregator.GetEvent<PubSubEventArgs>().Unsubscribe(GetScanBarCode);
            //base.OnNavigatedFrom(navigationContext);
        }

        private void GetScanBarCode(MessageData messageData)
        {
            if (messageData.Code == NonClientAreaControl._scanCode && messageData.Parameters.ContainsKey("Content")) {
                this.SearchText = messageData.Parameters.GetValue<string>("Content");
            }
        }

        #region 扫码枪相关-注释

        //private string _portStatus = "关闭";

        //public string PortStatus {
        //    get { return _portStatus; }
        //    set => SetProperty(ref _portStatus, value);
        //}

        //public DelegateCommand<string> ScanLinkCmd => new DelegateCommand<string>(rhs => Init(rhs));

        
        //private SerialPort _scanSerial;

        //private void Init(string cmd) {
        //    if (cmd == "Open") {
        //        Task.Run(() => {
        //            var packageScanConfig = _mainDbOperate.GetModel<PackageScanBarConfig>(p => true);
        //            if (PortStatus != "打开") {
        //                try {
        //                    PortStatus = "打开中";
        //                    if (_scanSerial == null) {
        //                        _scanSerial = new SerialPort();
        //                        _scanSerial.PortName = packageScanConfig.Port;
        //                        _scanSerial.BaudRate = 115200;
        //                        _scanSerial.DataBits = 8;
        //                        _scanSerial.StopBits = StopBits.One;
        //                        _scanSerial.Parity = Parity.None;
        //                        _scanSerial.DataReceived += _scanSerial_DataReceived;
        //                    }
        //                    _scanSerial.Close();
        //                    _scanSerial.Open();
        //                    if (_scanSerial.IsOpen) {
        //                        PortStatus = "打开";
        //                        //break;
        //                    }
        //                } catch (Exception ex) {
        //                    PortStatus = "打开失败，请重试！";
        //                }
        //            }
        //        });
        //    } else {
        //        if (_scanSerial != null) {
        //            _scanSerial?.Close();
        //            if (!_scanSerial.IsOpen) PortStatus = "关闭";
        //            _scanSerial?.Dispose();
        //        }
        //    }
        //}

        //private void _scanSerial_DataReceived(object sender, SerialDataReceivedEventArgs e) {
        //    Thread.Sleep(200);
        //    var lenght = _scanSerial.BytesToRead;
        //    var bytes = new byte[lenght];
        //    _scanSerial.Read(bytes, 0, lenght);
        //    var str = Encoding.UTF8.GetString(bytes).Replace("\n", "").Replace("\r", "");
        //    this.SearchText = str;
        //}
        #endregion

    }
}
